<template>
	<div class="default-main">

		<cus-form id="recipe-form" collapsable icon="fa fa-search" label="搜索">
			<template #title-after>
				<el-button icon="el-icon-Search" size="small" type="primary" @click.stop="handleSearch">
					搜索
				</el-button>
				<el-button icon="el-icon-Refresh" size="small" type="primary" @click.stop="resetSearch">
					重置
				</el-button>
			</template>
			<template #form>
				<el-form ref="recipeSearchFormRef" :model="params" label-width="auto">
					<el-row :gutter="20" justify="space-between">
						<el-col :span="5">
							<cus-form-title :show-divider="false" icon="local-cus-item" label="配方"></cus-form-title>
							<el-form-item label="配方名称" prop="recipeName_like">
								<el-input v-model="params.recipeName_like" clearable @keyup.enter="handleSearch"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="1">
							<el-divider border-style="dashed" direction="vertical" style="height: 100%"></el-divider>
						</el-col>
						<el-col :span="5">
							<cus-form-title :show-divider="false" icon="local-cus-item" label="原料"></cus-form-title>
							<el-form-item label="物品" prop="materialItemId">
								<el-select v-model="params.materialItemId" clearable filterable @change="handleSearch">
									<el-option v-for="item in itemOptionList" :key="item.id" :label="item.itemName!" :value="item.id">
										<span style="float: left">{{ item.itemName }}</span>
										<span v-if="item.image" style="float: right">
                  <el-image :src="getImage(item.image)" fit="contain" style="width: 30px; height: 30px"></el-image>
                </span>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="1">
							<el-divider border-style="dashed" direction="vertical" style="height: 100%"></el-divider>
						</el-col>
						<el-col :span="5">
							<cus-form-title :show-divider="false" icon="local-cus-item" label="产物（物品、建筑二选一）"></cus-form-title>
							<el-form-item label="物品" prop="productItemId">
								<el-select v-model="params.productItemId" clearable filterable @change="itemIdChanged">
									<el-option v-for="item in itemOptionList" :key="item.id" :label="item.itemName!" :value="item.id">
										<span style="float: left">{{ item.itemName }}</span>
										<span v-if="item.image" style="float: right">
                  <el-image :src="getImage(item.image)" fit="contain" style="width: 30px; height: 30px"></el-image>
                </span>
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="建筑" prop="productBuildingId">
								<el-select v-model="params.productBuildingId" clearable filterable @change="buildingIdChanged">
									<el-option v-for="building in buildingOptionList" :key="building.id" :label="building.buildingName!"
									           :value="building.id">
										<span style="float: left">{{ building.buildingName }}</span>
										<span v-if="building.image" style="float: right">
                  <el-image :src="getImage(building.image)" fit="contain" style="width: 30px; height: 30px"></el-image>
                </span>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="1">
							<el-divider border-style="dashed" direction="vertical" style="height: 100%"></el-divider>
						</el-col>
						<el-col :span="5">
							<cus-form-title :show-divider="false" icon="el-icon-OfficeBuilding" label="生产建筑"></cus-form-title>
							<el-form-item label="建筑" prop="productionBuildingId">
								<el-select v-model="params.productionBuildingId" clearable filterable @change="handleSearch">
									<el-option v-for="building in productionBuildingOptionList" :key="building.id"
									           :label="building.buildingName!" :value="building.id">
										<span style="float: left">{{ building.buildingName }}</span>
										<span v-if="building.image" style="float: right">
                  <el-image :src="getImage(building.image)" fit="contain"
                            style="width: 30px; height: 30px"
                  ></el-image>
                </span>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</template>
		</cus-form>

		<cus-table-title id="recipe-table-title" icon="local-cus-recipe" label="配方">
			<template #after>
				<el-button v-if="isAdmin()" icon="el-icon-Plus" size="small" style="margin-left: 20px" type="primary" @click="toAdd">
					新增
				</el-button>
			</template>
		</cus-table-title>
		<el-table v-loading="recipeTableLoading" :data="recipeTableData" :max-height="tableMaxHeight" border class="cus-table" fit highlight-current-row>
			<el-table-column align="center" label="序号" width="60">
				<template v-slot="scope">
					{{ initTableIndex(pageRef, scope.$index) }}
				</template>
			</el-table-column>
			<el-table-column align="center" label="配方" min-width="250">
				<template v-slot="scope">
					{{ scope.row.recipeNameDisplayed }}
				</template>
			</el-table-column>
			<el-table-column v-if="showRecipeSortColumn" align="center" label="同级排序" prop="sort" width="110"></el-table-column>
			<el-table-column align="center" label="原料" min-width="350">
				<template v-slot="scope">
					<p v-for="materialVo in scope.row.materialList" class="cus-center">
						<el-link :underline="false" type="primary" @click="showItemDetail(materialVo.itemId)">{{
								materialVo.itemName
							}}
						</el-link>
						{{ '*' + materialVo.quantityPerProduction }}
						<span v-if="materialVo.quantityPerMinute">{{ '（' + materialVo.quantityPerMinute + '/min）' }}</span>
						<el-image v-if="materialVo.image" :src="getImage(materialVo.image)" fit="contain"
						          style="margin-left: 10px; width: 50px; height: 50px; cursor: pointer"
						          @click="showItemDetail(materialVo.itemId)"></el-image>
					</p>
				</template>
			</el-table-column>
			<el-table-column align="center" label="产物" min-width="350">
				<template v-slot="scope">
					<p v-for="productVo in scope.row.productList" v-if="scope.row.productList.length > 0" class="cus-center">
						<el-link :underline="false" type="primary" @click="showItemDetail(productVo.itemId)">{{
								productVo.itemName
							}}
						</el-link>
						{{ '*' + productVo.quantityPerProduction }}
						{{ '（' + productVo.quantityPerMinute + '/min）' }}
						<el-image v-if="productVo.image" :src="getImage(productVo.image)" fit="contain"
						          style="margin-left: 10px; width: 50px; height: 50px; cursor: pointer"
						          @click="showItemDetail(productVo.itemId)"
						></el-image>
					</p>
					<p v-if="scope.row.buildingVo" class="cus-center">
						<el-link :underline="false" type="primary" @click="showBuildingDetail(scope.row.buildingVo.buildingId)">{{
								scope.row.buildingVo.buildingName
							}}
						</el-link>
						{{ '*' + 1 }}
						<el-image v-if="scope.row.buildingVo.image" :src="getImage(scope.row.buildingVo.image)"
						          fit="contain"
						          style="margin-left: 10px; width: 100px; height: 100px; cursor: pointer"
						          @click="showBuildingDetail(scope.row.buildingVo.buildingId)"
						></el-image>
					</p>
				</template>
			</el-table-column>
			<el-table-column v-if="showBuildingColumn" align="center" label="生产建筑" min-width="350">
				<template v-slot="scope">
					<p v-for="buildingVo in scope.row.buildingList" class="cus-center">
						<el-link :underline="false" type="primary" @click="showBuildingDetail(buildingVo.buildingId)">{{
								buildingVo.buildingName
							}}
						</el-link>
						{{
							(buildingVo.needPower === 1 ? '（' + buildingVo.power + 'MW' + (buildingVo.overclockable === 1 ? '，可超频' : '，不可超频') + '）' : '')
						}}
						<el-image v-if="buildingVo.image" :src="getImage(buildingVo.image)" fit="contain"
						          style="margin-left: 10px; width: 100px; height: 100px; cursor: pointer"
						          @click="showBuildingDetail(buildingVo.buildingId)"></el-image>
					</p>
				</template>
			</el-table-column>
			<el-table-column v-if="isAdmin()" :label="String($t('table.actions'))" align="center" fixed="right" width="120">
				<template v-slot="scope">
					<el-button icon="el-icon-Edit" size="small" type="primary" @click="toUpdate(scope.row)"></el-button>
					<el-popconfirm :hide-after="0" confirm-button-type="danger" title="删除该配方？"
					               width="auto" @confirm="deleteRecipe(scope.row)">
						<template #reference>
							<el-button v-auth="'g-recipe:deleteRecipe'" icon="el-icon-Delete" size="small"
							           type="danger"></el-button>
						</template>
					</el-popconfirm>
				</template>
			</el-table-column>
		</el-table>
		<cus-pagination id="recipe-pagination" ref="pageRef" v-model="recipeTableData" v-model:loading="recipeTableLoading"
		                :page-sizes="[5, 10, 20]" :pageSize="10"
		                :params="params" url="/game/g-recipe/readOnly/pageRecipe"
		                @refresh-done="showRecipeSortColumn = !!params.productItemId || !!params.productBuildingId; showBuildingColumn = !params.productBuildingId"/>

		<!-- 对话框（新增、修改） -->
		<el-dialog v-model="dialogVisible.edit" :close-on-click-modal="false" :close-on-press-escape="true" :title="dialogTitle" append-to-body center
		           class="cus-dialog" destroy-on-close draggable width="60%">
			<cus-form-title icon="local-cus-recipe" label="基本信息"/>
			<el-form ref="editFormRef" :model="recipe" :rules="editFormRules" label-width="auto">
				<el-row :gutter="20" justify="start">
					<el-col :span="8">
						<el-form-item label="产物类型" prop="productType">
							<el-select v-model="recipe.productType" :disabled="!!recipe.recipeId" clearable filterable @change="productTypeChanged">
								<el-option :value="1" label="物品"></el-option>
								<el-option :value="2" label="建筑"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="配方名称" prop="recipeName">
							<el-input v-model="recipe.recipeName" clearable maxlength="100"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="显示名称" prop="recipeNameDisplayed">
							<el-tag type="info">{{ recipe.recipeNameDisplayed || '/' }}</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20" justify="start">
					<el-col :span="8">
						<el-form-item label="同级排序" prop="sort">
							<el-input-number v-model="recipe.sort" :max="MAX_INTEGER" :min="1" :step="1" class="w100" controls-position="right" step-strictly/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<cus-table-title icon="local-cus-item" label="原料">
				<template #after>
					<el-button icon="el-icon-Plus" size="small" style="margin-left: 20px" type="primary" @click="addMaterial">
						添加
					</el-button>
				</template>
			</cus-table-title>
			<el-table :data="<MaterialVo[] & Material[]>recipe.materialList" border fit highlight-current-row max-height="400">
				<el-table-column align="center" label="序号" type="index" width="60"></el-table-column>
				<el-table-column align="center" label="物品" min-width="150">
					<template v-slot="scope">
						<el-select v-model="scope.row.item" clearable filterable value-key="id">
							<el-option v-for="item in itemOptionList" :key="item.id" :label="item.itemName!" :value="item">
								<span style="float: left">{{ item.itemName }}</span>
								<span v-if="item.image" style="float: right">
                  <el-image :src="getImage(item.image)" fit="contain" style="width: 30px; height: 30px"></el-image>
                </span>
							</el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column align="center" label="数量（/次）" min-width="150">
					<template v-slot="scope">
						<el-input-number v-model="scope.row.quantityPerProduction" class="w100" controls-position="right"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column v-if="recipe.productType === 1" align="center" label="数量（/min）" min-width="150">
					<template v-slot="scope">
						<el-input-number v-model="scope.row.quantityPerMinute" :min="0" :step="1" class="w100" controls-position="right" disabled
						                 placeholder="系统计算"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column :label="String($t('table.actions'))" align="center" width="100px">
					<template v-slot="scope">
						<el-button slot="reference" size="small" type="danger" @click="removeMaterial(scope.row)">
							<template #icon>
								<icon name="el-icon-Delete"></icon>
							</template>
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<cus-table-title icon="local-cus-item" label="产物">
				<template #after>
					<el-button v-if="recipe.productType === 1" icon="el-icon-Plus" size="small" style="margin-left: 20px" type="primary" @click="addProduct">
						添加
					</el-button>
				</template>
			</cus-table-title>
			<el-table v-if="recipe.productType === 1" :data="<ProductVo[] & Product[]>recipe.productList" border fit highlight-current-row max-height="400">
				<el-table-column align="center" label="序号" type="index" width="60"></el-table-column>
				<el-table-column align="center" label="物品" min-width="150">
					<template v-slot="scope">
						<el-select v-model="scope.row.item" clearable filterable value-key="id">
							<el-option v-for="item in itemOptionList" :key="item.id" :label="item.itemName!" :value="item">
								<span style="float: left">{{ item.itemName }}</span>
								<span v-if="item.image" style="float: right">
                  <el-image :src="getImage(item.image)" fit="contain" style="width: 30px; height: 30px"></el-image>
                </span>
							</el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column align="center" label="数量（/次）" min-width="150">
					<template v-slot="scope">
						<el-input-number v-model="scope.row.quantityPerProduction" class="w100" controls-position="right"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column v-if="recipe.productType === 1" align="center" label="数量（/min）（填写一种产物即可）"
				                 min-width="150">
					<template v-slot="scope">
						<el-input-number v-model="scope.row.quantityPerMinute" :min="0" :step="1" class="w100"
						                 controls-position="right"
						></el-input-number>
					</template>
				</el-table-column>
				<el-table-column :label="String($t('table.actions'))" align="center" width="100px">
					<template v-slot="scope">
						<el-button slot="reference" size="small" type="danger" @click="removeProduct(scope.row)">
							<template #icon>
								<icon name="el-icon-Delete"></icon>
							</template>
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-form v-if="recipe.productType === 2" ref="editFormForBuildingRef" :model="recipe"
			         :rules="editFormForBuildingRules" label-width="auto">
				<el-row :gutter="20" justify="center">
					<el-col :span="8">
						<el-form-item label="建筑" prop="buildingProduct">
							<el-select v-model="recipe.buildingProduct" clearable filterable value-key="id">
								<el-option v-for="building in buildingOptionList" :key="building.id" :label="building.buildingName!"
								           :value="building"
								>
									<span style="float: left">{{ building.buildingName }}</span>
									<span v-if="building.image" style="float: right">
                  <el-image :src="getImage(building.image)" fit="contain"
                            style="width: 30px; height: 30px"
                  ></el-image>
                </span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="功率" prop="power">
							<el-tag type="info">
								{{
									recipe.buildingProduct ? (recipe.buildingProduct as BuildingProduct & GBuilding).power + ' MW' : '/'
								}}
							</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="超频" prop="overclockable">
							<el-tag type="info">
								{{
									recipe.buildingProduct ? ((recipe.buildingProduct as BuildingProduct & GBuilding).overclockable === 1 ? '能' : '不能') : '/'
								}}
							</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<cus-table-title v-if="recipe.productType === 1" icon="el-icon-OfficeBuilding" label="生产建筑">
				<template #after>
					<el-button v-if="recipe.productType === 1" icon="el-icon-Plus" size="small" style="margin-left: 20px"
					           type="primary" @click="addBuilding">
						添加
					</el-button>
				</template>
			</cus-table-title>
			<el-table v-if="recipe.productType === 1" :data="<RecipeBuildingVo[] & Building[]>recipe.buildingList" border fit
			          highlight-current-row max-height="400">
				<el-table-column align="center" label="序号" type="index" width="60"></el-table-column>
				<el-table-column align="center" label="建筑" min-width="150">
					<template v-slot="scope">
						<el-select v-model="scope.row.building" clearable filterable value-key="id"
						           @change="selectedBuildingChanged(scope.row.building, scope.row)">
							<el-option v-for="building in productionBuildingOptionList" :key="building.id"
							           :label="building.buildingName!" :value="building"
							>
								<span style="float: left">{{ building.buildingName }}</span>
								<span v-if="building.image" style="float: right">
                  <el-image :src="getImage(building.image)" fit="contain" style="width: 30px; height: 30px"></el-image>
                </span>
							</el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column align="center" label="功率（MW）" min-width="150" prop="power"></el-table-column>
				<el-table-column align="center" label="超频" min-width="150" prop="overclockable"></el-table-column>
				<el-table-column :label="String($t('table.actions'))" align="center" width="100px">
					<template v-slot="scope">
						<el-button slot="reference" size="small" type="danger" @click="removeBuilding(scope.row)">
							<template #icon>
								<icon name="el-icon-Delete"></icon>
							</template>
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<template #footer>
				<el-button v-auth="'g-recipe:saveRecipe'" icon="el-icon-CircleCheck" type="primary" @click="save">
					保存
				</el-button>
				<el-button icon="el-icon-CircleClose" type="warning" @click="dialogVisible.edit = false">
					取消
				</el-button>
			</template>
		</el-dialog>

		<!-- 对话框（物品详情） -->
		<cus-item-dialog v-model:visible="dialogVisible.item" :item-id="itemIdDisplayed" @searchRecipe="searchRecipe"/>

		<!-- 对话框（建筑详情） -->
		<cus-building-dialog v-model:visible="dialogVisible.building" :building-id="buildingIdDisplayed" @searchRecipe="searchRecipe"/>

	</div>
</template>

<script lang="ts" name="Recipe" setup>

import {onActivated, onMounted, reactive, ref} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {
	deleteRecipeApi,
	getAllBuildingApi,
	getAllItemApi,
	getAllProductionBuildingApi,
	saveRecipeForBuildingApi,
	saveRecipeForItemApi
} from '@/api/gameData/recipe.api'
import {exist, focusFormErrorElement, getImage, initTableIndex, messageSuccess} from '@/utils/commonUtil'
import {useI18n} from 'vue-i18n'
import CusItemDialog from '@/components/cus-item-dialog.vue'
import CusBuildingDialog from '@/components/cus-building-dialog.vue'
import CusTableTitle from '@/components/cus-table-title.vue'
import CusFormTitle from '@/components/cus-form-title.vue'
import CusPagination from '@/components/cus-pagination.vue'
import Icon from '@/components/icon.vue'
import {calcMaxHeight} from '@/utils/layoutUtil'
import type {DebouncedFunc} from 'lodash-es'
import {debounce} from 'lodash-es'
import {useEventListener} from '@vueuse/core'
import {onBeforeRouteLeave} from 'vue-router'
import {MAX_INTEGER} from '@/utils/constantsUtil'
import {isAdmin} from '@/utils/authUtil'
import {useRouteParamsStore} from '@/stores/modules/routeParams.store'
import CusForm from '@/components/cus-form.vue'

const {t} = useI18n()
const routeParamsStore = useRouteParamsStore()

const pageRef = ref()
const recipeSearchFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()
const editFormForBuildingRef = ref<FormInstance>()

const params = reactive<SearchRecipeRequest>({
	productItemId: undefined,
	productBuildingId: undefined,
	materialItemId: undefined,
	productionBuildingId: undefined,
	recipeName_like: undefined
})
const paramsLastTime = reactive<typeof params>({
	productItemId: undefined,
	productBuildingId: undefined,
	materialItemId: undefined,
	productionBuildingId: undefined,
	recipeName_like: undefined
})
const itemOptionList = ref<GItem[]>([])
const buildingOptionList = ref<GBuilding[]>([])
const productionBuildingOptionList = ref<GBuilding[]>([])
const recipeTableData = ref<SearchRecipeVo[]>([])
const recipeTableLoading = ref(false)
const tableMaxHeight = ref<number>(800)
const showRecipeSortColumn = ref(false)
const showBuildingColumn = ref(true)
const dialogVisible = reactive({
	item: false,
	building: false,
	edit: false
})
const itemIdDisplayed = ref<number>()
const buildingIdDisplayed = ref<number>()
const recipe = reactive<SearchRecipeVo & SaveRecipeRequest>({
	recipeId: undefined,
	recipeName: undefined,
	recipeNameDisplayed: undefined,
	productType: 1,
	sort: MAX_INTEGER,
	materialList: [],
	productList: [],
	buildingProduct: undefined,
	buildingList: []
})
const dialogTitle = ref<string>()
const editFormRules = reactive<FormRules>({
	recipeName: [
		{required: true, message: '请填写配方名称', trigger: 'change'}
	],
	productType: [
		{required: true, message: '请选择产物类型', trigger: 'change'}
	],
	sort: [
		{required: true, message: '请填写同级排序', trigger: 'change'}
	]
})
const editFormForBuildingRules = reactive<FormRules>({
	buildingProduct: [
		{required: true, message: '请选择产物', trigger: 'change'}
	]
})

// 计算表格最大高度
const getTableMaxHeight: DebouncedFunc<() => typeof getTableMaxHeight> = debounce(() => {
	tableMaxHeight.value = calcMaxHeight('#recipe-form', '#recipe-table-title', '#recipe-pagination')
	return getTableMaxHeight
}, 100, {
	leading: true,
	trailing: false,
	maxWait: 100
})

const itemIdChanged = (val: number) => {
	if (val) {
		params.productBuildingId = undefined
	}
	handleSearch()
}

const buildingIdChanged = (val: number) => {
	if (val) {
		params.productItemId = undefined
	}
	handleSearch()
}

const memoryParams = () => {
	paramsLastTime.productItemId = params.productItemId
	paramsLastTime.productBuildingId = params.productBuildingId
	paramsLastTime.materialItemId = params.materialItemId
	paramsLastTime.productionBuildingId = params.productionBuildingId
	paramsLastTime.recipeName_like = params.recipeName_like
}

const applyLastParams = () => {
	params.productItemId = paramsLastTime.productItemId
	params.productBuildingId = paramsLastTime.productBuildingId
	params.materialItemId = paramsLastTime.materialItemId
	params.productionBuildingId = paramsLastTime.productionBuildingId
	params.recipeName_like = paramsLastTime.recipeName_like
}

const handleSearch = debounce((currentPage?: boolean) => {
	memoryParams()
	if (currentPage === true) {
		pageRef.value.buildData()
	} else {
		pageRef.value.reload()
	}
}, 500, {
	leading: true,
	trailing: false,
	maxWait: 500
})

const resetParams = () => {
	params.productItemId = undefined
	params.productBuildingId = undefined
	params.materialItemId = undefined
	params.productionBuildingId = undefined
	params.recipeName_like = undefined
}

const resetSearch = () => {
	resetParams()
	handleSearch()
}

const showItemDetail = (itemId: number) => {
	itemIdDisplayed.value = itemId
	dialogVisible.item = true
}

const showBuildingDetail = (buildingId: number) => {
	buildingIdDisplayed.value = buildingId
	dialogVisible.building = true
}

const resetRecipe = (productType?: SaveRecipeRequest['productType']) => {
	recipe.recipeId = undefined
	recipe.recipeName = undefined
	recipe.recipeNameDisplayed = undefined
	recipe.productType = productType ?? 1
	recipe.sort = MAX_INTEGER
	recipe.materialList = []
	recipe.productList = []
	recipe.buildingProduct = undefined
	recipe.buildingList = []
}

const toAdd = () => {
	if (paramsLastTime.productBuildingId) {
		resetRecipe(2)
	} else {
		resetRecipe()
	}
	dialogVisible.edit = true
	dialogTitle.value = '新增配方'
}

const toUpdate = (row: SearchRecipeVo) => {
	if (row.buildingVo) {
		resetRecipe(2)
	} else {
		resetRecipe()
	}
	Object.assign(recipe, JSON.parse(JSON.stringify(row)))
	for (const material of recipe.materialList!) {
		Reflect.set(material, 'item', {
			id: material.itemId,
			itemName: material.itemName
		})
	}
	if (row.buildingVo) {
		Reflect.set(recipe, 'buildingProduct', {
			id: row.buildingVo.buildingId!,
			buildingName: row.buildingVo.buildingName!,
			power: row.buildingVo.power
		})
	} else {
		for (const product of recipe.productList) {
			Reflect.set(product, 'item', {
				id: product.itemId,
				itemName: product.itemName
			})
		}
		for (const building of recipe.buildingList) {
			Reflect.set(building, 'building', {
				id: building.buildingId,
				buildingName: building.buildingName
			})
			Reflect.set(building, 'power', building.power === 0 ? '/' : building.power)
			Reflect.set(building, 'overclockable', building.overclockable === 1 ? '能' : '不能')
		}
	}
	dialogVisible.edit = true
	dialogTitle.value = '编辑配方信息'
}

const save = () => {
	editFormRef.value!.validate(pass => {
		if (pass) {
			// 产物是建筑
			if (editFormForBuildingRef.value) {
				editFormForBuildingRef.value.validate(pass => {
					if (pass) {
						saveRecipeForBuildingApi(recipe).then(() => {
							if (recipe.recipeId) {
								messageSuccess(t('successMessage.update'))
							} else {
								messageSuccess(t('successMessage.add'))
							}
							dialogVisible.edit = false
							applyLastParams()
							handleSearch(true)
						})
					} else {
						focusFormErrorElement()
					}
				})
			}
			// 产物是物品
			else {
				saveRecipeForItemApi(recipe).then(() => {
					if (recipe.recipeId) {
						messageSuccess(t('successMessage.update'))
					} else {
						messageSuccess(t('successMessage.add'))
					}
					dialogVisible.edit = false
					applyLastParams()
					handleSearch(true)
				})
			}
		} else {
			focusFormErrorElement()
		}
	})
}

const deleteRecipe = (row: SearchRecipeVo) => {
	deleteRecipeApi(row.recipeId!).then(() => {
		messageSuccess(t('successMessage.delete'))
		applyLastParams()
		handleSearch(true)
	})
}

const addMaterial = () => {
	recipe.materialList.push({
		item: {
			id: undefined,
			itemName: undefined
		},
		quantityPerProduction: undefined,
		quantityPerMinute: undefined
	})
}

const addProduct = () => {
	recipe.productList.push({
		item: {
			id: undefined,
			itemName: undefined
		},
		quantityPerProduction: undefined,
		quantityPerMinute: undefined
	})
}

const addBuilding = () => {
	recipe.buildingList.push({
		building: {
			id: undefined,
			buildingName: undefined
		}
	})
}

const removeMaterial = (row: Material) => {
	recipe.materialList.splice(recipe.materialList.indexOf(row), 1)
}

const removeProduct = (row: Product) => {
	recipe.productList.splice(recipe.productList.indexOf(row), 1)
}

const removeBuilding = (row: Building) => {
	recipe.buildingList.splice(recipe.buildingList.indexOf(row), 1)
}

const selectedBuildingChanged = (val: GBuilding, row: Building & RecipeBuildingVo) => {
	if (val) {
		Reflect.set(row, 'power', val.power === 0 ? '/' : val.power)
		Reflect.set(row, 'overclockable', val.overclockable === 1 ? '能' : '不能')
	} else {
		Reflect.set(row, 'power', undefined)
		Reflect.set(row, 'overclockable', undefined)
	}
}

const productTypeChanged = (val: SaveRecipeRequest['productType']) => {
	resetRecipe(val)
}

const searchRecipe = (searchParams?: SearchRecipeRequest) => {
	if (searchParams) {
		Object.assign(params, searchParams)
	}
	handleSearch()
}

const checkRouteQuery = (): boolean => {
	const routeParams = routeParamsStore.getParams()
	try {
		if (routeParams && (exist(routeParams.materialItemId) || exist(routeParams.productItemId) || exist(routeParams.productBuildingId) || exist(routeParams.productionBuildingId))) {
			params.materialItemId = routeParams.materialItemId ? Number(routeParams.materialItemId) : undefined
			params.productItemId = routeParams.productItemId ? Number(routeParams.productItemId) : undefined
			params.productBuildingId = routeParams.productBuildingId ? Number(routeParams.productBuildingId) : undefined
			params.productionBuildingId = routeParams.productionBuildingId ? Number(routeParams.productionBuildingId) : undefined
			return true
		}
		return false
	} catch (e) {
		console.error(e)
		return false
	} finally {
		routeParamsStore.removeParams()
	}
}

getAllItemApi().then(response => {
	itemOptionList.value = response.data
})
getAllBuildingApi().then(response => {
	buildingOptionList.value = response.data
})
getAllProductionBuildingApi().then(response => {
	productionBuildingOptionList.value = response.data
})

checkRouteQuery()

onMounted(() => {
	useEventListener(window, 'resize', getTableMaxHeight()!)
})

// 该页面开启缓存且首次或后续进入时执行，刷新页面不执行
onActivated(() => {
	useEventListener(window, 'resize', getTableMaxHeight()!)
	if (checkRouteQuery()) {
		handleSearch()
	}
})

onBeforeRouteLeave(() => {
	window.removeEventListener('resize', getTableMaxHeight)
})

</script>

<style lang="scss" scoped>
</style>
